package com.wetao.lib_common.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.wetao.lib_common.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;
    private Context context;
    private String TAG = "下载页面";

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new RetryIntercepter(3))//添加Stetho的拦截器
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    /**
     * @param url 下载连接
     * @param saveDir 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void download(Context context, final String url, final String saveDir, final OnDownloadListener listener) {
        this.context= context;


        // 需要token的时候可以这样做
        // SharedPreferences sp=MyApp.getAppContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        // Request request = new Request.Builder().header("token",sp.getString("token" , "")).url(url).build();

//        File file1 = new File(saveDir, getNameFromUrl(url));
//        if (file1.exists()){
//            Log.w(TAG,"下载目录："+file1.getAbsolutePath());
//            listener.onDownloadSuccess(file1.getAbsolutePath());
//            return;
//
//        }



        if(!ComUtil.isNetworkConnected()){
            if(null != listener) {
                listener.onNetwork(false);
            }
            return;
        }

        Request request = new Request.Builder().url(url).tag(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
                cancelTag(url);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[1024];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                //String savePath = isExistDir(saveDir);
               // Log.w(TAG,"存储下载目录："+savePath);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(saveDir, getNameFromUrl(url));
                    Log.w(TAG,"最终路径："+file);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading((int)sum,(int)total,progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file.getAbsolutePath());
                } catch (Exception e) {
                    listener.onDownloadFailed();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                    cancelTag(url);
                }
            }
        });
    }


    /**
     * @param context
     * @param url
     * @param saveDir
     * @param savePath  保存的文件地址
     * @param listener
     */
    public void download(Context context, final String url, final String saveDir,final String savePath, final OnDownloadListener listener) {
        this.context= context;


        // 需要token的时候可以这样做
        // SharedPreferences sp=MyApp.getAppContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        // Request request = new Request.Builder().header("token",sp.getString("token" , "")).url(url).build();

//        File file1 = new File(saveDir, getNameFromUrl(url));
//        if (file1.exists()){
//            Log.w(TAG,"下载目录："+file1.getAbsolutePath());
//            listener.onDownloadSuccess(file1.getAbsolutePath());
//            return;
//
//        }

        if(!ComUtil.isNetworkConnected()){
            if(null != listener) {
                listener.onNetwork(false);
            }
            return;
        }

        Request request = new Request.Builder().url(url).tag(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
                cancelTag(url);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[1024];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                //String savePath = isExistDir(saveDir);
               // Log.w(TAG,"存储下载目录："+savePath);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(saveDir, getNameFromUrl(savePath));
                    Log.w(TAG,"最终路径："+file);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading((int)sum,(int)total,progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file.getAbsolutePath());
                } catch (Exception e) {
                    listener.onDownloadFailed();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                    cancelTag(url);
                }
            }
        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException
     * 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        //File downloadFile = new File(Environment.getExternalStorageDirectory().getPath() + "/download/", saveDir);
        File downloadFile = new File(Constants.FILE_PATH + "/download/", saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        Log.w(TAG,"下载目录："+savePath);
        return savePath;
    }




    /** 根据Tag取消请求 */
    public void cancelTag(Object tag) {
        if (tag == null) return;
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : okHttpClient.dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }

    /** 根据Tag判断请求是否运行 */
    public synchronized boolean getTagCall(String tag) {

        boolean isTag=false;

        Log.w(TAG,"tag：---"+tag);
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            Log.w(TAG,"下载tag：---"+call.request().tag());
            if (tag.equals(call.request().tag())) {
                isTag=true;
                break;
            }
        }
        for (Call call : okHttpClient.dispatcher().runningCalls()) {
            Log.w(TAG,"下载tag：=="+call.request().tag());
            if (tag.equals(call.request().tag())) {
                isTag=true;
                break;
            }
        }
        return isTag;
    }


    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    public static String getNameFromUrl(String url) {


        if (TextUtils.isEmpty(url)) {
            return null;
        }
        int start = url.lastIndexOf("/");
        if (-1 == start) {
            return null;
        }
        return url.substring(start + 1);
    }


    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess(String path);

        /**
         * @param progress
         * 下载进度
         */
        void onDownloading(int sum, int total, int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();

        void onNetwork(boolean isNetwork);
    }
    /**
     * 重试拦截器
     */
    public class RetryIntercepter implements Interceptor {

        public int maxRetry;//最大重试次数
        private int retryNum = 0;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

        public RetryIntercepter(int maxRetry) {
            this.maxRetry = maxRetry;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            System.out.println("retryNum=" + retryNum);
            Response response = chain.proceed(request);
            while (!response.isSuccessful() && retryNum < maxRetry) {
                retryNum++;
                System.out.println("retryNum=" + retryNum);
                response = chain.proceed(request);
            }
            return response;
        }
    }
}
